package com.lxb.myforum.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;

import com.lxb.myforum.pojo.Authority;
import com.lxb.myforum.pojo.Resource;
import com.lxb.myforum.repository.ResourceRepository;

/**
 * 
 * @author lxb
 *
 */
@Component("mySecurityMetadataSource")
public class CustomInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

	@Autowired
	private ResourceRepository resourceRepository;
	
	/**
	 * key : url value : 权限集合
	 */
	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	/**
	 * 加载资源
	 */
	@PostConstruct
	private void loadResourceDefine() {
		if (resourceMap == null) {
			resourceMap = new HashMap<>();
		}

		// 1.查找所有权限资源
		Iterable<Resource> resources = resourceRepository.findAll();
		// 2.查找资源需要角色
		for (Resource resource : resources) {
			 // 该角色所有的权限
			Collection<Authority> authorities = resource.getAuthorities();

			List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>(authorities.size());
			for (Authority authority : authorities) {
				// 权限的名字唯一
				attributes.add(new SecurityConfig(authority.getName()));
			}
			System.out.println("[" + resource.getUrl() + "] need roles: " + attributes);
			resourceMap.put(resource.getUrl(), attributes);
		}
	}

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		FilterInvocation filterInvocation = ((FilterInvocation) object);
		// 将参数转为url
		// String url = ((FilterInvocation) object).getRequestUrl();
		// 循环已有的角色配置对象 进行url匹配
		for (String resURL : resourceMap.keySet()) {
			System.out.println("resUrl = [" + resURL + "]");
			RequestMatcher urlMatcher = new AntPathRequestMatcher(resURL);
			if (urlMatcher.matches(filterInvocation.getHttpRequest())) {
				System.out.println("url: [" + resURL + "] need roles: " + resourceMap.get(resURL));
				return resourceMap.get(resURL);
			}
		}
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return true;
	}
}
